package com.vegetable.modules.entity.finance;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.format.annotation.DateTimeFormat;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="银行流水对象", description="银行流水对象")
public class Transactions {
    // 加密字符串
    @TableField(exist = false)
    private static String secretKey = "deshuo";
    @ApiModelProperty("主键id")
    @JsonSerialize(using = ToStringSerializer.class)
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @ApiModelProperty("交易唯一ID")
    private String tradingNo;
    @ApiModelProperty("商户订单号")
    private String orderNo;
    @ApiModelProperty("交易时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private Date tradingTime;
    @ApiModelProperty("交易金额")
    private BigDecimal tradingAmount;
    @ApiModelProperty("账户逾额")
    private BigDecimal balanceAmount;
    @ApiModelProperty("手续费")
    private String fee;
    @ApiModelProperty("交易类型 'INCOME','EXPENSE','REFUND'")
    private String tradingType;
    @ApiModelProperty("交易状态 'SUCCESS','FAILED','PROCESSING'")
    private String status;
    @ApiModelProperty("支付渠道 'WECHAT','ALIPAY','BANK'")
    private String channel;
    @ApiModelProperty("对方银行名称")
    private String bankName;
    @ApiModelProperty("对方银行卡ID")
    private String bankNo;
    @ApiModelProperty("商户ID")
    private String merchantId;
    @ApiModelProperty("交易对手方")
    private String counterparty;
    @ApiModelProperty("交易描述")
    private String tradingDescription;
    @ApiModelProperty("关联账户id")
    private Long fundAccountId;
    @ApiModelProperty("关联账户名称")
    private String fundAccountName;
    @ApiModelProperty("备注")
    private String remark;
    @ApiModelProperty("流水归属id")
    private Long abId;
    @ApiModelProperty("流水归属id")
    private String abName;
    @ApiModelProperty("系统人员添加的描述")
    private String sysRemark;

    @ApiModelProperty("已匹配金额总和")
    private BigDecimal matchedAmount;

    private String tradingFlag;

    private String rawData;

    private String uniqueMark;

    // 在原有类中添加以下方法
    public static void sortByTradingTimeDesc(List<Transactions> list) {
        Collections.sort(list, new Comparator<Transactions>() {
            @Override
            public int compare(Transactions t1, Transactions t2) {
                // 处理可能的null值：将null时间视为最小值（排在最后）
                if (t1.getTradingTime() == null && t2.getTradingTime() == null) {
                    return 0;
                } else if (t1.getTradingTime() == null) {
                    return 1; // t1排在t2后面
                } else if (t2.getTradingTime() == null) {
                    return -1; // t1排在t2前面
                }
                // 倒序排列：最近的时间在前
                return t2.getTradingTime().compareTo(t1.getTradingTime());
            }
        });
    }


    public static String generateUniqueFlowId(Transactions trans) throws Exception {
        Date tradingTime = trans.getTradingTime();
        BigDecimal tradingAmount = trans.getTradingAmount();
        BigDecimal balanceAmount = trans.getBalanceAmount();
        String bankNo = trans.getBankNo();
        String status = trans.getStatus();
        String counterparty = trans.getCounterparty();

        // 1. 提取并格式化字段
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStr = tradingTime != null ? sdf.format(tradingTime) : "";
        String amountStr = tradingAmount != null ? tradingAmount.stripTrailingZeros().toPlainString() : "";
        String balanceStr = balanceAmount != null ? balanceAmount.stripTrailingZeros().toPlainString() : "";
        String bankStr = bankNo != null ? bankNo : "";
        String statusStr = status != null ? status : "";
        String party = StrUtil.isNotBlank(counterparty) ? counterparty : "";

        // 2. 拼接字段（使用|分隔，避免冲突）
        String rawData = String.join("|",
                timeStr, amountStr, balanceStr, bankStr, statusStr, party);

        // 3. md5编码返回
        return DigestUtil.md5Hex(rawData);
    }
}
